var i = 1;
var totalPage = "";
$(function(){
	InitSupply();
	var token=localStorage.getItem("token");
	gridObj = $.fn.bsgrid.init('g_tabYeh', {
		ajaxType : 'post',
		url :  server_url+'/rest/saleManager/skuProductList.do?ran=' + Math.random() + '&token=' + token,
		autoLoad : true,
		pageSizeSelect : true,
		stripeRows : true,
		pageSize : 10,
		displayBlankRows : false,
		isProcessLockScreen : true,
		rowSelectedColor : false,
		showPageToolbar:true,
		rowHoverColor:true
	});	
	/*InitSaleData(i);
	$("#g_tabYeh_pt_nextPage").live("click",function(){
		i++;
		console.log("当前第多少页:"+i);
		console.log("当前总页数:"+totalPage);
		if(i>totalPage){
			i = totalPage;
			return;
		}else{
			InitSaleData(i);
		}	
	});
	$("#g_tabYeh_pt_prevPage").live("click",function(){
		i--;
		if(i<1){
			i = 1;
			return;
		}else{
			InitSaleData(i);
		}
	});
	$("#g_tabYeh_pt_lastPage").live("click",function(){
		i = totalPage;
		InitSaleData(i);
	});
	$("#g_tabYeh_pt_firstPage").live("click",function(){
		i = 1;
		InitSaleData(i);
	});
	$("#g_tabYeh_pt_gotoPage").live("click",function(){
		if($("#g_tabYeh_pt_gotoPageInput").val()>totalPage){
			return;
		}else{
			i = $("#g_tabYeh_pt_gotoPageInput").val();
			InitSaleData(i);
		}	
	});*/
	
});
function InitSaleData(i){
	var userdatas = [];
	userdatas.success = true;
	userdatas.curPage = i;
	var data_formate = '{"data":{"total":10,"curPage":'+i+',"rows":';
	var params = {};
	var productName = $("#productName").val();
	var buyerAreaName = $("#buyerAreaName").val();
	var supplyName = $("#supplyName").val();
	/*var provinceName = $("#provinceId").val();
	var cityName = $("#cityId").val();*/
	var countyId = $("#countyId").val();
	params["productName"] = productName ;
	params["buyerAreaName"] = buyerAreaName;
	params["supplyName"] = supplyName;
	params["countyId"] = countyId;
	$.ajax({
		type : 'post',
		url  :  server_url+'rest/saleManager/skuProductList.do?ran=' + Math.random() + '&token=' + token,
		data:params,
		async:false,
		success : function(data) {
			if(data.retCode=="0000"||data.retCode=="0002"){
				var datastr = "";
				if(data.data!=null){
					datastr=data.data;
				}
				var treejson = JSON.stringify(datastr);
				data_formate = data_formate+ treejson;
			}
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					    content : data.retMsg
					  },
					  autoClose : 2000
					});
				
			} 
			
		}
	});
	data_formate = data_formate + '},"retCode":"0000","retMsg":"\u64cd\u4f5c\u6210\u529f"}';
	userdata = $.parseJSON(data_formate);
	var sdfs = getItemData(userdata.data.rows);
	userdatas.totalRows = userdata.data.rows.total;
	//console.log(sdfs.length);
	userdatas.data = sdfs;
	gridObj.loadGridData('json', userdatas);
	totalPage = $("#g_tabYeh_pt_totalPages").text();
}
function getItemData(datas) {
	var sdfs = [];
	if (typeof (datas) == "object") {
		$.each(datas.rows, function(i, data) {
				var p = {};
				p.id = data.id;
				p.productName = data.productName;
				p.supplyName = data.supplyName;
				p.isOffStatus = data.isOffStatus;
				p.price = data.price;
				p.overPlusNum = data.overPlusNum;
				p.saleType = data.saleType;
				p.saleStatus = data.saleStatus;
				p.approveStatus = data.approveStatus;
				p.buyerAreaName = '<div>';
				var areaIds = data.areaId;
				if(areaIds == null || areaIds == ''){
					if(data.saleType == "定向到买家"){
						p.buyerAreaName = '<a href="javascript:toBuyerInfo('+data.buyerId+')">'+data.buyerName+'</a></div>';
					}
					if(p.saleStatus == '5' ){
						p.buyerAreaName ='全国卖家';
					}
					if(p.saleStatus == '6'){
						p.buyerAreaName ='全国买家';
					}
				}else{
					if(data.saleType == "非定向"){
						p.buyerAreaName = '</div>';
					}else{
						//console.log(p.saleStatus);
						var areaId = areaIds.split(",");
						replaceEmptyItem(areaId);
						for(var i = 0;i<areaId.length;i++){
							$.ajax({
								url:server_url+'rest/saleManager/getAreaName.do?areaId='+areaId[i],
								type:'post',
								async:false,
								success:function(dataes){
									p.buyerAreaName += dataes.data.data[0].buyerAreaName+"</div>";
								}
							})
						}
					}
				}
				sdfs.push(p);
		});
		}
	return sdfs;
};

function operate(record, rowIndex, colIndex, options) {
	if(gridObj.getRecordIndexValue(record, 'isOffStatus')=="上架"){
       return  '<a href="javascript:modifySkuProduct(\'' + gridObj.getRecordIndexValue(record, 'id') +'\');">修改</a>'+
		        '<a href="javascript:sureStatusSwitchs(\'' + gridObj.getRecordIndexValue(record, 'id') + '\',\''+ gridObj.getRecordIndexValue(record, 'isOffStatus')+'\');">下架</a>'+
                '<a href="javascript:viewSkuProductInfo(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">审核</a>'+
		        '<a href="javascript:skuProductLog(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">操作历史</a>';
	}else{
	  return  '<a href="javascript:modifySkuProduct(\'' + gridObj.getRecordIndexValue(record, 'id') +'\');">修改</a>'+
		       '<a href="javascript:sureCancel(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">取消发布</a><a href="javascript:sureStatusSwitch(\'' + gridObj.getRecordIndexValue(record, 'id') + '\',\''+ gridObj.getRecordIndexValue(record, 'isOffStatus')+'\');");">上架</a>'+
	           '<a href="javascript:viewSkuProductInfo(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">审核</a>'+
		       '<a href="javascript:skuProductLog(\'' + gridObj.getRecordIndexValue(record, 'id') + '\');">操作历史</a>';
	}
   
};


function replaceEmptyItem(arr){
    for(var i=0,len=arr.length;i<len;i++){
        if(!arr[i]|| arr[i]==''){
            arr.splice(i,1);
            len--;
             
        }
    }
};
//跳转到卖家信息
function toBuyerInfo(id){
	var url='buyerInfo.do?id='+id;
	tl_config.loadToWorkArea(url);
};
//跳转到发布商品信息
function viewSkuProductInfo(id){
	var url='skuProductInfo.do?id='+id;
	tl_config.loadToWorkArea(url);
}
//跳转到修改发布商品信息
function modifySkuProduct(id){
	var url='skuProductEdit.do?id='+id;
	tl_config.loadToWorkArea(url);
}
//跳转到操作历史
function skuProductLog(id){
	var url='skuProductLog.do?id='+id;
	tl_config.loadToWorkArea(url);
}
// 数据表格参数查询
function doSearch() {
	var searchParames = $('#myform').serialize();
	console.log(searchParames);
	gridObj.search(searchParames);	
}

function InitSupply(){
	var html="<option value='' selected='selected'>请选择</option>";
	$(html).appendTo("#supplyName");
	$.ajax({
		url:server_url+'/rest/supplyManage/supplyListNoPage.do?ran='+Math.random()+"&token="+token,
		type:'get',
		success:function(data){
			if(data.retCode=="0000"){
				for(var i=0;i<data.data.length;i++){
					var html ="<option value='"+data.data[i].supplyName+"'>"+data.data[i].supplyName+"</option>";
					$(html).appendTo("#supplyName");
				}
			}
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					      content : data.retMsg
					  },
					  autoClose : 2000
					});				
			} 			
		}
	});	
}
/*$("#province").change(function(){
	areaParentChange("city", $(this).val(),"county");
});
$("#city").change(function(){
	areaParentChange("county", $(this).val());
});*/
/*$("#county").change(function(){
	areaParentChange("accountCity", $(this).val());
});*/
/*function InitProvince(){
	
}*/
//获取checkbox选中批量下架
function statusSwitchs() {
	var ids = gridObj.getCheckedValues('id').toString();
	var isOffStatus = gridObj.getCheckedValues('isOffStatus').toString()
	if (ids == "") {
		easyDialog.open({
			container:{
				header:'温馨提示',
				content:"请选择要操作的记录！"
			},
			autoClose : 2000
		});
	} else {
		sureStatusSwitchs(ids,isOffStatus);
	}
}
//下架
function sureStatusSwitchs(ids,isOffStatus){
	easyDialog.open({
		  container : {
			header:'温馨提示',
		    content : '您确定要下架吗？',
		    yesFn : function(){
		    	$.ajax({
					url : server_url+'/rest/saleManager/changeStatusSwitchs.do',
					type : 'post',
					dataType : 'json',
					data : {
						isOffStatus:isOffStatus,
						ids : ids,
						token:token
					},
					success : function(data) {
						if (data.retCode = "0000") {								
							var url="skuProductList.do?ran="+Math.random();
							tl_config.loadToWorkArea(url);
						} else{
							easyDialog.open({
								container:{header:'温馨提示',content:data.retMsg},
								autoClose : 2000
							});
						}  
					}
				});
		    },
		    noFn : true
		  }
		});
	
}
//上架
function sureStatusSwitch(id,isOffStatus){
	easyDialog.open({
		  container : {
			header:'温馨提示',
		    content : '您确定要上架吗？',
		    yesFn : function(){
		    	$.ajax({
					url : server_url+'/rest/saleManager/changeStatusSwitch.do',
					type : 'post',
					dataType : 'json',
					data : {
						isOffStatus:isOffStatus,
						ids : id,
						token:token
					},
					success : function(data) {
						if (data.retCode = "0000") {								
							var url="skuProductList.do?ran="+Math.random();
							tl_config.loadToWorkArea(url);
						} else{
							easyDialog.open({
								container:{header:'温馨提示',content:data.retMsg},
								autoClose : 2000
							});
						}  
					}
				});
		    },
		    noFn : true
		  }
		});
	
}
//获取checkbox选中取消发布
function cancel() {
	var ids = gridObj.getCheckedValues('id').toString();
	if (ids == "") {
		easyDialog.open({
			container:{
				header:'温馨提示',
				content:"请选择要操作的记录！"
			},
			autoClose : 2000
		});
	} else {
		sureCancel(ids);
		
	}
}
function sureCancel(ids){
	easyDialog.open({
		  container : {
			header:'温馨提示',
		    content : '您确定要取消吗？',
		    yesFn : function(){
		    	$.ajax({
					url : server_url+'/rest/saleManager/skuProductCancel.do',
					type : 'post',
					dataType : 'json',
					data : {
						ids : ids,
						token:token
					},
					success : function(data) {
						if (data.retCode = "0000") {
							var url="skuProductList.do?ran="+Math.random();
							tl_config.loadToWorkArea(url);
						} else{
							easyDialog.open({
								container:{header:'温馨提示',content:data.retMsg},
								autoClose : 2000
							});
						}  
					}
				});
		    },
		    noFn : true
		  }
		});
};
function toSaleProductAdd(){
	var url="skuProductAdd.do?ran="+Math.random();
	tl_config.loadToWorkArea(url);
}
function toSaleProductAdd1(){
	var url="skuProductAdd1.do?ran="+Math.random();
	tl_config.loadToWorkArea(url);
}